var mongodb = require('mongodb');

var client = new mongodb.Db('myrpg', new mongodb.Server("127.0.0.1", 27017, {}));

var users = null;
var characters = null;

client.open(function(err, p_client) {
    if(err)
        console.warn(err.message);
    else{
        p_client.collection('users', function (err, collection) {
            users = collection;
        });
        p_client.collection('characters', function (err, collection) {
            characters = collection;
        });
    }  
});

exports.getAll = function(callback){
    characters.find().toArray(callback);
};

exports.getAllForUser = function(user, callback){
    characters.find({
        owner:user.username
    }).toArray(callback);
};

exports.getByName = function(name, callback){
    characters.find({
        name:name
    }).nextObject(callback);
};

exports.addCharacter = function(user, chara, callback){
    characters.find({
        name:chara.name
    }).nextObject(function(err, object){
        if(err){
            callback(err);
        }else if(object){
            var error = {};
            error.message = "duplicate character error!" + object.name;
            callback(error);
        }else{
            characters.insert(chara, {
                safe:true
            }, function(err, objects){
                if(err){
                    callback(err);
                }else {
                    users.findAndModify({
                        username:user.username
                    },[],{
                        $push:{
                            characters:chara.name
                        }
                    },{},function(err, obj){
                        callback(null, objects[0]);
                    });
                }
            });
        }
    }); 
};

exports.save = function(character){
    characters.save(character);
};
